﻿@using Gurux.DLMS.AMI.Shared
@using Gurux.DLMS.AMI.Shared.DIs
@using Gurux.DLMS.AMI.Shared.DTOs.Enums
@using Gurux.DLMS.AMI.Shared.Enums
@using Gurux.DLMS.ManufacturerSettings
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using Gurux.DLMS.AMI.Shared.DTOs
@using Gurux.DLMS.AMI.Shared.Rest
@using Microsoft.AspNetCore.SignalR.Client
@using Gurux.DLMS.AMI.Client.Helpers
@using Gurux.DLMS.AMI.Module
@using System.Text.Json

@namespace Gurux.DLMS.AMI.Client.Pages.Config

@inject NavigationManager NavigationManager
@inject HttpClient Http
@inject IGXNotifier Notifier
@inject ConfirmBase Confirm
@implements IDisposable
@implements IGXConfigUpdate

@if (string.Compare(Action, "Add", true) == 0 ||
string.Compare(Action, "Edit", true) == 0 ||
string.Compare(Action, "Remove", true) == 0)
{
    <Authentication Parent="this"
                Id="@Id"
                Action="@Action"></Authentication>
}
else @if (_authentications != null)
{
    <MenuControl RightCorner="true">
        <ChildContent>
            <MenuItem Text="@Properties.Resources.Add" Icon="oi oi-plus" OnClick="@OnAdd" />
        </ChildContent>
    </MenuControl>

    <GXTable @ref="table"
         Context="item"
         ItemsProvider="@GetItems"
         SelectionMode="SelectionMode.Single"
         Filter="@false">
        <FilterContent>
        </FilterContent>
        <MenuContent>
            <AuthorizeView Roles=@GXRoles.ToString(GXRoles.Admin, GXRoles.BlockGroupManager)>
                <ContextMenuItem Text="@Properties.Resources.Edit" Icon="oi oi-pencil" OnClick="@OnEdit"></ContextMenuItem>
                <ContextMenuItem Text="@Properties.Resources.Remove" Icon="oi oi-trash" OnClick="@OnRemove"></ContextMenuItem>
            </AuthorizeView>
        </MenuContent>
        <HeaderContent>
            <Th Id="Name">@Properties.Resources.Name</Th>
            <Th Id="ClientId">Client ID</Th>
        </HeaderContent>
        <ItemContent>
            <Td Link="@("Config/Authentication/Edit/" + item.Name)">@item.Name</Td>
            <td>@item.ClientId</td>
        </ItemContent>
    </GXTable>
    <br />
}
@code {
    /// <summary>
    /// Parent component.
    /// </summary>
    [Parameter]
    public Gurux.DLMS.AMI.Client.Pages.Config.Configurations? Parent { get; set; }

    /// <summary>
    /// User action.
    /// </summary>
    [Parameter]
    public string? Action { get; set; }

    /// <summary>
    /// Selected item.
    /// </summary>
    [Parameter]
    public string? Id { get; set; }

    /// <summary>
    /// Table reference.
    /// </summary>
    protected GXTable<AuthenticationSettings>? table;

    private List<AuthenticationSettings> _authentications = new List<AuthenticationSettings>();

    /// <summary>
    /// Get available authentications.
    /// </summary>
    /// <returns></returns>
    public List<AuthenticationSettings> GetAuthentications()
    {
        return _authentications;
    }

    /// <inheritdoc/>
    public void Update()
    {
        if (!string.IsNullOrEmpty(Parent?.Active?.Settings))
        {
            var items = JsonSerializer.Deserialize<AuthenticationSettings[]>(Parent.Active.Settings);
            if (items != null)
            {
                _authentications.AddRange(items);
            }
        }
        StateHasChanged();
    }

    private async ValueTask<ItemsProviderResult<AuthenticationSettings>> GetItems(GXItemsProviderRequest request)
    {
        return new ItemsProviderResult<AuthenticationSettings>(_authentications, _authentications.Count);
    }

    protected override void OnInitialized()
    {
        if (NavigationManager.ToBaseRelativePath(NavigationManager.Uri).StartsWith("Authentication/"))
        {
            //If authentication is shown or edit.
            return;
        }
        try
        {
            Notifier.ProgressStart();
            Notifier.ClearStatus();
            Notifier.Clear();
            Notifier.UpdateButtons();
            if (!string.IsNullOrEmpty(Parent?.Active?.Settings))
            {
                var items = JsonSerializer.Deserialize<AuthenticationSettings[]>(Parent.Active.Settings);
                if (items != null)
                {
                    _authentications.AddRange(items);
                }
            }
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
        finally
        {
            Notifier?.ProgressEnd();
        }
    }

    /// <summary>
    /// Delete selected authentications.
    /// </summary>

    public void OnRemove()
    {
        try
        {
            Notifier.ClearStatus();
            if (table?.Active == null)
            {
                throw new Exception(Gurux.DLMS.AMI.Client.Properties.Resources.NoItemIsSelected);
            }
            ClientHelpers.NavigateTo(NavigationManager, Notifier, "/Config/Authentication/Remove/" + table.Active.Name);
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    /// <summary>
    /// Add new authentication.
    /// </summary>
    public void OnAdd()
    {
        try
        {
            Notifier.ClearStatus();
            ClientHelpers.NavigateTo(NavigationManager, Notifier, "Config/Authentication/Add");
        }
        catch (AccessTokenNotAvailableException exception)
        {
            exception.Redirect();
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    /// <summary>
    /// Edit authentication.
    /// </summary>
    public void OnEdit()
    {
        try
        {
            Notifier.ClearStatus();
            if (table?.Active == null)
            {
                throw new Exception(Gurux.DLMS.AMI.Client.Properties.Resources.NoItemIsSelected);
            }
            ClientHelpers.NavigateTo(NavigationManager, Notifier, "/Config/Authentication/Edit/" + table.Active.Name);
        }
        catch (Exception ex)
        {
            Notifier?.ProcessError(ex);
        }
    }

    public void Dispose()
    {
        Notifier.RemoveListener(this);
    }
}
